<script setup>
import { ref } from 'vue'
import api from '@/api'
import { Message, useFormItem } from '@arco-design/web-vue'

const props = defineProps(['modelValue', 'dir', 'accepts', 'maxSize'])
const emit = defineEmits(['update:modelValue', 'change'])
const { mergedDisabled, eventHandlers } = useFormItem()

const progress = ref(100)

const uploadRequest = async (option) => {
  try {
    progress.value = 0
    const resp = await api.post('oss/url', {
      filename: option.fileItem.name,
      dir: props.dir,
    })
    let data = new FormData()
    data.append('key', resp.key)
    data.append('OSSAccessKeyId', resp.id)
    data.append('policy', resp.policy)
    data.append('signature', resp.signature)
    data.append('file', option.fileItem.file)
    const xhr = new XMLHttpRequest()
    xhr.open('POST', resp.host, true)
    xhr.upload.onprogress = (e) => {
      progress.value = Math.floor((e.loaded / e.total) * 100)
    }
    xhr.onerror = () => {
      progress.value = 100
      Message.error('上传失败!')
    }
    xhr.onload = async () => {
      progress.value = 100
      if (xhr.status !== 204) {
        Message.error('上传失败!')
        return
      }
      emit('update:modelValue', resp.url)
      emit('change', resp.url)
      eventHandlers.value?.onInput?.(resp.url)
    }
    xhr.send(data)
  } catch (error) {
    progress.value = 100
    console.error(error)
    Message.error('上传失败!')
  }
}

const beforeUpload = (file) => {
  Message.clear()
  if (!props.accepts.includes(file.type)) {
    Message.error('文件格式不符合要求')
    return false
  } else if (file.size > props.maxSize * 1024 * 1024) {
    Message.error(`文件大小不能超过 ${props.maxSize}MB!`)
    return false
  }
  return true
}
</script>

<template>
  <a-upload
    :accept="accepts.join(',')"
    :custom-request="uploadRequest"
    @before-upload="beforeUpload"
    :show-file-list="false"
    :disabled="progress < 100"
  >
    <template v-if="progress < 100" #upload-button>
      <a-button loading type="primary">上传中 {{ progress }}%</a-button>
    </template>
  </a-upload>
</template>

<style lang="scss" scoped></style>
